--
-- Author: shunguo.chen
-- Date: 2018-08-14 14:09:32
--
-- LoadingModel
--

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ModelBase)

local FileUtils = cc.FileUtils:getInstance()
local TextureCache = cc.Director:getInstance():getTextureCache()

local SPLIT_STEP = 5

function ClassRef:ctor(data)
    self.super.ctor(self, data)
end

function ClassRef:init()

end

function ClassRef:getMapLoadingTips()
    return GD:randomLoadingTips()
end

function ClassRef:getMapLoadingImg(mapId)
	return GD:randomLoadingImage(mapId)
end

-- 设置玩法id, 如果是角色扮演玩法，需要预加载角色
function ClassRef:setPlayId(id)
    self._playId = id
end
-- 获取玩法id
function ClassRef:getPlayId()
    return self._playId
end

function ClassRef:getLoadTextureTasks(mapId)
	local tasks = {}

	local mapPath = "scripts.mapconfig." .. "map_" .. mapId
	local mapConfig = app:loadResScript(mapPath)
	local mapConf = mapConfig.config

	-- 加载图片
    if mapConf.mapPath then
        local tempList = cc.CSLoader:fetchTextures(mapConf.mapPath)
        local textureList  = {}
        for _,tex in pairs(tempList) do
        	if FileUtils:isFileExist(tex) then
        		table.insert(textureList,tex)
        	end
        end
        
        local textureLen = #textureList

        local step = 1
        while step <= textureLen do
        	local paths = {}
        	for i=0, SPLIT_STEP-1 do
        		local idx = i+step
        		if idx>textureLen then
        			break
        		end
        		table.insert(paths,textureList[idx])
        	end

        	if #paths>0 then
	        	table.insert(tasks,function() 
	                for i=1,#paths do
	                	local filePath = paths[i]
                		TextureCache:addImage(filePath)
	            	end
	            end)
        	end

        	step = step + SPLIT_STEP
        end
    end

    -- 加载音乐
    if mapConf.music then
    	table.insert(tasks,function()
    		AM.preload(mapConf.music)
    	end)
    end

    -- 加载图集
    if mapConf.sheets then
    	local sharedSpriteFrameCache = cc.SpriteFrameCache:getInstance()
    	for _,sheetFolder in pairs(mapConfig.config.sheets) do
	    	for i=0,15,1 do
	    		local sheetFile = sheetFolder..i..".plist"
	    		if FileUtils:isFileExist(sheetFile) then
	    			table.insert(tasks,function() 
	    				sharedSpriteFrameCache:addSpriteFrames(sheetFile)
	            	end)
	    		end
	    	end
    	end
    end

    -- 加载npc资源
    local confs = GD:queryMapsetBaseByMapId(mapId)
    local AvatarFactory = app:getClass("AvatarFactory")
    if confs and AvatarFactory then
        for _, conf in pairs(confs) do
            if conf.modelShow == "1" then
    			table.insert(tasks,function() 
    				AvatarFactory.preloadNpcById(conf.ID)
            	end)
            end
        end
    end

    return tasks
end

------------------------ receive ------------------------


------------------------ request ------------------------

return ClassRef
